package user

import (
	"context"
	"grpc-common/api/user/personal"
	"time"
	"user-api/api/user"
	"user-api/internal/logic"
	"user-api/utility"
)

type personalLogic struct {
}

func NewPersonalLogic() *personalLogic {
	return &personalLogic{}
}

func (p *personalLogic) Login(ctx context.Context, req *user.LoginReq) (res *user.LoginRes, err error) {
	//查询用户信息
	person, err := logic.RpcCli.PersonalClient.GetUserByMobile(ctx, &personal.MobileRequest{
		Mobile: req.Mobile,
	})
	if err != nil {
		return &user.LoginRes{}, err
	}
	//校验密码
	checkRes, err := logic.RpcCli.PersonalClient.CheckPassWord(ctx, &personal.PasswordCheckInfo{
		Password:          req.Password,
		EncryptedPassword: person.Password,
		Salt:              person.Salt,
	})
	if checkRes.Success {
		token, err := utility.GetJwtToken("123456", time.Now().Unix(), 86400, int64(person.Id))
		if err != nil {
			return &user.LoginRes{
				UserId: int64(person.Id),
				Token:  "generate jwt token error",
			}, nil
		}
		return &user.LoginRes{
			UserId: int64(person.Id),
			Token:  token,
		}, nil
	}
	return &user.LoginRes{
		UserId: int64(person.Id),
		Token:  "error",
	}, nil
}

func (p *personalLogic) CreateUser(ctx context.Context, req *user.CreateUserReq) (*user.CreateUserRes, error) {
	createUser, err := logic.RpcCli.PersonalClient.CreateUser(ctx, &personal.CreateUserInfo{
		Nickname: req.Nickname,
		Password: req.Password,
		Mobile:   req.Mobile,
	})
	if err != nil {
		return &user.CreateUserRes{}, err
	}
	return &user.CreateUserRes{
		UserId: int64(createUser.Id),
	}, nil
}

func (p *personalLogic) UpdateUser(ctx context.Context, req *user.UpdateUserReq) (*user.UpdateUserRes, error) {
	return &user.UpdateUserRes{
		UserId:  0,
		Success: true,
	}, nil
}

func (p *personalLogic) UserList(ctx context.Context, req *user.UserPageReq) (*user.UserPageRes, error) {
	userInfos := make([]*user.UserInfoRes, 0)
	return &user.UserPageRes{
		Total:     0,
		Page:      0,
		Size:      0,
		UserInfos: userInfos,
	}, nil
}

func (p *personalLogic) UserInfo(ctx context.Context, req *user.UserInfoReq) (*user.UserInfoRes, error) {
	return &user.UserInfoRes{
		Id:       0,
		Nickname: "",
		Password: "",
		Mobile:   "",
		Birthday: "",
		Role:     "",
	}, nil
}

func (p *personalLogic) DeleteUser(ctx context.Context, req *user.DeleteUserReq) (*user.DeleteUserRes, error) {
	return &user.DeleteUserRes{
		UserId:  0,
		Success: true,
	}, nil
}
